package airwallex

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"simplifly-tech/payment/consts"
	model2 "simplifly-tech/payment/model"
	"strconv"
	"strings"
	"time"
)

func (airwallexService *AirwallexService) Notify(ctx *gin.Context) (*model2.PaymentNotification, error) {

	allRespStr, err := ctx.GetRawData()
	if err != nil {
		return nil, err
	}

	var reqData AirwallexReqData
	if err = json.Unmarshal(allRespStr, &reqData); err != nil {
		return nil, err
	}

	xTimestamp := ctx.GetHeader("x-timestamp")
	xSignature := ctx.GetHeader("x-signature")

	if xTimestamp == "" || xSignature == "" {
		return nil, errors.New("x-signature error")
	}

	bodyStr := xTimestamp + string(allRespStr)
	newSign := ComputeHMAC(airwallexService.PayServerKey, bodyStr)

	if newSign != xSignature {
		return nil, errors.New("x-signature error")
	}

	orderIdArr := strings.Split(reqData.Data.Object.MerchantOrderId, "-")
	status := consts.NotifyStatusFailed
	if reqData.Data.Object.Status == "SUCCEEDED" {
		status = consts.NotifyStatusSuccess
	}
	paidAt, _ := time.Parse("2006-01-02T15:04:05", reqData.Data.Object.CreatedAt[0:19])
	incomeId, _ := strconv.ParseUint(orderIdArr[1], 10, 64)

	return &model2.PaymentNotification{
		Status:       status,
		OrderID:      orderIdArr[0],
		IncomeID:     uint(incomeId),
		PaidAt:       paidAt,
		AsyncPayment: true,
		ReferenceID:  reqData.Data.Object.Id,
	}, nil

}

func (airwallexService *AirwallexService) RefundNotify(ctx *gin.Context) (*model2.NotifyResponse, error) {
	allRespStr, err := ctx.GetRawData()
	if err != nil {
		return nil, err
	}
	var reqData AirWallexRefundNotofy
	if err = json.Unmarshal(allRespStr, &reqData); err != nil {

		return nil, err
	}

	xTimestamp := ctx.GetHeader("x-timestamp")
	xSignature := ctx.GetHeader("x-signature")

	if xTimestamp == "" || xSignature == "" {
		return nil, errors.New("signature error")
	}

	reqDataJson, err := json.Marshal(reqData)
	if err != nil {
		return nil, err
	}
	bodyStr := xTimestamp + string(reqDataJson)
	newSign := ComputeHMAC(airwallexService.RefundServerKey, bodyStr)
	if newSign != xSignature {
		return nil, errors.New("signature error")
	}
	if reqData.Data.Object.Status != "ACCEPTED" && reqData.Data.Object.Status != "SUCCEEDED" { //accepted
		return nil, errors.New("not success")
	}

	paidAt, _ := time.Parse("2006-01-02T15:04:05", reqData.Data.Object.CreatedAt[0:19])
	return &model2.NotifyResponse{
		PaidAt: &paidAt,
		Paid:   reqData.Data.Object.Amount.Neg(),
	}, nil
}
